package com.spring.cold.controller;

import com.github.pagehelper.PageInfo;
import com.spring.cold.common.ApiReturn;
import com.spring.cold.common.LayReturn;
import com.spring.cold.pojo.User;
import com.spring.cold.security.Securitys;
import com.spring.cold.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import static com.spring.cold.common.EntityWrapper.*;

/**
 * @author jy
 * @date 2020-10-16
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/showRegister")
    public String showRegister(){
        return "/register";
    }

    @RequestMapping(PAGE)
    public String page(){
        return "views/user/list";
    }

    @RequestMapping("/form")
    public String form(Model model){
        model.addAttribute("user",userService.selectByPrimaryKey(Securitys.getUserId()));
        return "views/user/form";
    }

    @RequestMapping(NEW)
    @ResponseBody
    public ApiReturn save(User user){
        if (userService.selectByLoginName(user.getLoginName())!=null){
            return ApiReturn.error("此账号已被注册！");
        }
        user.setIsAdmin("0");
        return userService.insertSelective(wrap(user))>0?ApiReturn.success("注册成功！"):ApiReturn.error("注册失败！");
    }

    @RequestMapping(UPTATE)
    @ResponseBody
    public ApiReturn uptate(User user){
        return userService.updateByPrimaryKeySelective(wrap(user))>0?ApiReturn.success("修改成功！"):ApiReturn.error("修改失败！");
    }

    @RequestMapping(LIST)
    @ResponseBody
    public LayReturn list(User user){
        PageInfo<User> page = userService.selectPage(user);
        return LayReturn.success(page.getTotal(),page.getList());
        //return LayReturn.error();
    }

    @RequestMapping(DELETE_ID)
    @ResponseBody
    public ApiReturn delete(@PathVariable("id")String id){
        return userService.deleteByPrimaryKey(id)>0?ApiReturn.success("删除成功！"):ApiReturn.error("删除失败！");
    }

    @RequestMapping(SHOW_ID)
    public String show(@PathVariable("id")String id, Model model){
        model.addAttribute("user",userService.selectByPrimaryKey(id));
        return "views/user/new";
    }
}
